﻿using DiscussProject.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DiscussProject.Controllers
{
    public class FileUploadController : Controller
    {
        [HttpPost]
        public ActionResult UploadImage()
        {
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase img = Request.Files["head_photo"];
                string fileType = Path.GetExtension(img.FileName);//获取扩展名
                string serverPath = Server.MapPath("~/Images/");
                //看看文件夹是否存在
                if (!Directory.Exists(serverPath))
                {
                    Directory.CreateDirectory(serverPath);
                }
                if (fileType == null)
                {
                    TempData["set_ret"] = "请检查上传的文件是否正常!";
                    return RedirectToAction("Set", "User");
                }
                fileType = fileType.ToLower();
                if ("(.gif)|(.jpg)|(.bmp)|(.jpeg)|(.png)".Contains(fileType))
                {
                    //生成一个随机值 避免命名冲突；
                    string fileName = System.Guid.NewGuid().ToString();
                    fileName += fileType;
                    img.SaveAs(serverPath + fileName);
                    //获取当前usr 并将头像URL存入数据库
                    var usr = UserMapper.QueryUserByUid((int)Session["Id"]);
                    usr.Picture = "../Images/" + fileName;
                    Session["head_img"] = usr.Picture;
                    UserMapper.UpdateUser(usr);
                    return RedirectToAction("Index", "User");
                }
                else
                {
                    TempData["set_ret"] = "只支持上传图片!";
                    return RedirectToAction("Set", "User");
                }
            }
            TempData["set_ret"] = "上传的图片不能为空!";
            return RedirectToAction("Set", "User");
        }

    }
}